//
//  SingleAlubumBrowerViewController.m
//  Logistics
//
//  Created by 刘峰 on 2017/12/11.
//  Copyright © 2017年 com.Logistics. All rights reserved.
//

#import "SingleAlubumBrowerViewController.h"
#import "PhotoEditorViewController.h"
#import "SinglePictureViewCell.h"
#import "PhotoBrowerManager.h"

#define GapSpacing  (3 * KscreenWidth/320)

@interface SingleAlubumBrowerViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, SinglePictureViewCellDelegate>

{
    BOOL firstEnter;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomHeightLayout;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *selectedAssets;
@property (nonatomic, strong) NSMutableDictionary *imageDictionary;

@end

@implementation SingleAlubumBrowerViewController

static NSString * const reuseIdentifier = @"SinglePictureViewCell";


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = self.bwrObject.albumtitle;
    // Register cell classes
    if (IS_IPHONEX) {
        _topLayout.constant = 88;
        _bottomHeightLayout.constant = 50 + 34;
    }
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"SinglePictureViewCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    
    if (@available(iOS 11.0, *)) {
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }

}

-(void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    if (self.bwrObject.AssetList.count > 0 && !firstEnter) {
        firstEnter = YES;
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.bwrObject.AssetList.count-1 inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.bwrObject.AssetList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SinglePictureViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.delegate = self;
    
    PHAsset *asset = self.bwrObject.AssetList[indexPath.item];
    if ([self.selectedAssets containsObject:asset]) {
        cell.selectBtn.selected = YES;
    }else {
        cell.selectBtn.selected = NO;
    }
    [cell photoAsset:asset Original:NO imageOption:self.imageDictionary];
    
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((KscreenWidth - GapSpacing * 5)/4, (KscreenWidth - GapSpacing * 5)/4);
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return GapSpacing;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return GapSpacing;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(GapSpacing, GapSpacing, GapSpacing, GapSpacing);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SinglePictureViewCell *cell = (SinglePictureViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    if (cell.selectBtn.selected) {
        [self previewAction:nil];
    }else {
        PHAsset *asset = self.bwrObject.AssetList[indexPath.item];
        [self selectedPictureAsset:asset Sender:cell.selectBtn];
    }
    
}

-(void)selectedPictureAsset:(PHAsset *)asset Sender:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected && self.selectedAssets.count >= [PhotoBrowerManager defaultManager].maxLimit) {
        sender.selected = NO;
        [[LFAlertBox defaultAlert] showAlertTitle:nil content:@{@"text":[NSString stringWithFormat:@"最多只能选择%ld张照片",self.selectedAssets.count], @"font":[UIFont boldSystemFontOfSize:17], @"textColor":KGMBLACK_COLOR} cancleBtn:nil sureBtn:@{@"text":@"我知道了"} completion:nil];
        return;
    }
    if ([self.selectedAssets containsObject:asset]) {
        [self.selectedAssets removeObject:asset];
    }else {
        [self.selectedAssets addObject:asset];
    }
}

// 预览
- (IBAction)previewAction:(id)sender {
    if (self.selectedAssets.count > 0) {
        PhotoEditorViewController *editor = [[PhotoEditorViewController alloc] init];
        editor.assetList  = self.selectedAssets;
        [self.navigationController pushViewController:editor animated:YES];
    }else {
        [GRHUD showMessage:@"请选择相片" atView:self.view];
    }
}

// 使用
- (IBAction)usePicturesAction:(UIButton *)sender {
    
    if (self.selectedAssets.count > 0) {
        sender.enabled = NO;
        [GRHUD showProgress:@"正在处理" atView:self.view];
        WEAKSELF
        [PHAsset getOriginalImagesWithAssets:self.selectedAssets AssetBlock:^(NSArray<UIImage *> *images) {
            [GRHUD dismissHUD:weakSelf.view];
            [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationDidFinishIMAGE object:weakSelf userInfo:@{@"images":images}];
            [weakSelf dismissALLViewController];
        }];
        
    }else {
        [GRHUD showMessage:@"请选择相片" atView:self.view];
    }
}



#pragma Mark - - 懒加载
-(NSMutableDictionary *)imageDictionary {
    if (!_imageDictionary) {
        _imageDictionary = [NSMutableDictionary dictionary];
    }
    return _imageDictionary;
}

-(NSMutableArray *)selectedAssets {
    if (!_selectedAssets) {
        _selectedAssets = [NSMutableArray array];
    }
    return _selectedAssets;
}



@end
